import { shallowReactive, ref, Ref, h, resolveComponent } from 'vue';
import {
  AppMobPortletProps,
  IAppActionSheetButton,
  IAppActionSheetOptions,
  ICtrlActionResult,
  IMobPortletController,
  IParam,
  Util,
} from 'ibz-core';
import { CtrlComponentBase } from './ctrl-component-base';
import { GenerateComponent } from '../component-base';
import {
  IPSAppMenu,
  IPSControl,
  IPSDBAppViewPortletPart,
  IPSDBHtmlPortletPart,
  IPSDBMenuPortletPart,
  IPSDBRawItemPortletPart,
} from '@ibiz/dynamic-model-api';

/**
 * 移动端门户部件
 *
 * @class AppMobPortlet
 */
export class AppMobPortlet extends CtrlComponentBase<AppMobPortletProps> {
  /**
   * 移动端门户部件控制器实例对象
   *
   * @type {IMobPortletController}
   * @memberof AppMobPortlet
   */
  protected c!: IMobPortletController;

  /**
   * UUID
   *
   * @type {string}
   * @memberof AppMobPortlet
   */
  private uuid: string = Util.createUUID();

  /**
   * 操作按钮集合
   *
   * @type {Ref<IParam[]}
   * @memberof AppMobPortlet
   */
  public actionSheetButtons: Ref<IParam> = ref([]);

  /**
   * 行为操作显示状态
   *
   * @type {Ref<IParam[]}
   * @memberof AppMobPortlet
   */
  public actionSheetShowStatus: Ref<boolean> = ref(false);

  /**
   * 设置响应式
   *
   * @memberof AppMobPortlet
   */
  setup() {
    this.c = shallowReactive<IMobPortletController>(this.getCtrlControllerByType('PORTLET') as IMobPortletController);
    super.setup();
  }

  /**
   * 获取门户部件大小
   * @memberof AppMobPortlet
   */
  public getSize(): IParam {
    const size = {};
    const { height, width } = this.c.controlInstance;
    if (height) {
      Object.assign(size, { height: height + 'px' });
    }
    if (width) {
      Object.assign(size, { width: width + 'px' });
    }
    return size;
  }

  /**
   * 打开动作面板
   *
   * @param event 源事件对象
   * @memberof AppMobPortlet
   */
  public openActionSheet(event: any) {
    const buttons: IAppActionSheetButton[] = [];
    this.c.actionBarModel.forEach((model: any) => {
      buttons.push({
        text: model.name,
        icon: model.icon,
        handler: () => {
          this.onActionBarItemClick(model.viewLogicName, event);
        },
      });
    });
    buttons.push({
      text: this.$tl('share.cancel', '取消'),
      role: 'cancel',
      handler: () => {},
    });
    const options: IAppActionSheetOptions = { buttons: buttons };
    App.getActionSheetService()
      .create(options)
      .then((result: ICtrlActionResult) => {});
  }

  /**
   * 操作栏按钮点击
   *
   * @param {string} tag 标识
   * @param {*} event 源事件对象
   * @memberof AppMobPortlet
   */
  public onActionBarItemClick(tag: string, event?: any) {
    if (this.c.actionBarItemClick && this.c.actionBarItemClick instanceof Function) {
      this.c.actionBarItemClick(tag, event);
    }
  }

  /**
   * 渲染部件
   *
   * @memberof AppMobPortlet
   */
  public renderControl() {
    const controls = this.c.controlInstance.getPSControls?.();
    if (controls) {
      return controls.map((control: IPSControl) => {
        return this.computeTargetCtrlData(control);
      });
    }
  }

  /**
   * 渲染直接内容
   *
   * @memberof AppMobPortlet
   */
  public renderRawItem() {
    const { rawItemHeight, rawItemWidth, contentType, rawContent, htmlContent } = this.c
      .controlInstance as IPSDBRawItemPortletPart;
    const sysCss = this.c.controlInstance.getPSSysCss();
    const sysImage = this.c.controlInstance.getPSSysImage();
    const rawStyle =
      (rawItemHeight > 0 ? `height:${rawItemHeight}px` : '') + (rawItemWidth > 0 ? `width:${rawItemWidth}px` : '');
    const newRawContent = rawContent;
    if (rawContent) {
      //  TODO  国际化内容支持
      // const items = rawContent.match(/\{{(.+?)\}}/g);
      // if (items) {
      //     items.forEach((item: string) => {
      //       rawContent = rawContent.replace(/\{{(.+?)\}}/, item.substring(2, item.length - 2));
      //     });
      // }
    }
    let element: any = undefined;
    if (contentType == 'HTML' && htmlContent) {
      element = h('div', {
        innerHTML: htmlContent,
      });
    }
    let content: any;
    switch (contentType) {
      case 'HTML':
        content = element ? element : htmlContent;
        break;
      case 'RAW':
        content = rawContent;
        break;
      case 'IMAGE':
        content = <img src={sysImage?.imagePath} />;
        break;
      case 'MARKDOWN':
        content = <div>{this.$tl('widget.mobportlet.nomarkdown', 'MARKDOWN直接内容暂未支持')}</div>;
        break;
    }
    return content;
  }

  /**
   * 渲染HTML内容
   *
   * @memberof AppMobPortlet
   */
  public renderHtml() {
    const height = this.c.controlInstance.height > 0 ? this.c.controlInstance.height : 400;
    const pageUrl = (this.c.controlInstance as IPSDBHtmlPortletPart).pageUrl;
    const iframeStyle = `height: ${height - 26}px; width: 100%; border-width: 0px;`;
    return <iframe src={pageUrl} style={iframeStyle}></iframe>;
  }

  /**
   * 渲染工具栏
   *
   * @memberof AppMobPortlet
   */
  public renderToolbar() {
    return <div>{this.$tl('widget.mobportlet.toolbar', '工具栏')}</div>;
  }

  /**
   * 渲染操作栏
   *
   * @memberof AppMobPortlet
   */
  public renderActionBar() {
    return h(resolveComponent('app-actionbar'), {
      items: this.c.actionBarModel,
      modelService: this.c.modelService,
      onItemClick: (tag: string, event: any) => {
        this.onActionBarItemClick(tag, event);
      },
    });
  }

  /**
   * 渲染自定义内容
   *
   * @memberof AppMobPortlet
   */
  public renderCustom() {
    return <div>{this.$tl('widget.mobportlet.rendercustom', '绘制自定义')}</div>;
  }

  /**
   * 渲染应用菜单
   *
   * @memberof AppMobPortlet
   */
  public renderAppMenu() {
    const menu = (this.c.controlInstance as IPSDBMenuPortletPart).getPSControls()?.[0] as IPSAppMenu;
    if (menu) {
      return this.computeTargetCtrlData(menu, { ctrlShowMode: 'QUICKMENU', modelData: menu });
    }
  }

  /**
   * 渲染视图
   *
   * @memberof AppMobPortlet
   */
  public renderView() {
    const portletView = (this.c.controlInstance as IPSDBAppViewPortletPart)?.getPortletPSAppView();
    const targetViewComponent = portletView
      ? App.getComponentService().getViewTypeComponent(
          portletView?.viewType,
          portletView?.viewStyle,
          portletView?.getPSSysPFPlugin()?.pluginCode,
        )
      : '';
    return (
      <div class='portlet-view-container'>
        {targetViewComponent
          ? h(targetViewComponent, {
              key: this.uuid,
              class: `portlet-view`,
              viewPath: portletView?.modelPath,
              viewShowMode: 'EMBEDDED',
              navContext: Util.deepCopy(this.c.context),
              navParam: Util.deepCopy(this.c.viewParam),
              isLoadDefault: false,
              viewState: this.c.viewState,
              modelData: portletView,
              onViewEvent: ({ viewName, action, data }: { viewName: string; action: string; data: any }) => {
                this.c.handleViewEvent(viewName, action, data);
              },
            })
          : null}
      </div>
    );
  }

  /**
   * 根据门户部件类型渲染内容
   *
   * @memberof AppMobPortlet
   */
  public renderByPortletType() {
    switch (this.c.controlInstance.portletType) {
      case 'VIEW':
        return this.renderView();
      case 'APPMENU':
        return this.renderAppMenu();
      case 'CUSTOM':
        return this.renderCustom();
      case 'ACTIONBAR':
        return this.renderActionBar();
      case 'TOOLBAR':
        return this.renderToolbar();
      case 'HTML':
        return this.renderHtml();
      case 'RAWITEM':
        return this.renderRawItem();
      default:
        return this.renderControl();
    }
  }

  /**
   * 渲染标题
   *
   * @memberof AppMobPortlet
   */
  public renderTitle() {
    const { title, showTitleBar } = this.c.controlInstance;
    const sysImage = this.c.controlInstance.getPSSysImage();
    const showTitle = (showTitleBar && title) || this.c.actionBarModel.length > 0;
    if (showTitle) {
      return (
        <ion-card-header class='portlet-header'>
          <app-icon icon={sysImage}></app-icon>
          <span>{this.$tl(this.c.controlInstance?.getTitlePSLanguageRes()?.lanResTag, title)}</span>
          {this.c.actionBarModel.length > 0 ? (
            <div class='portlet-header-action'>
              <app-icon
                name='ellipsis-horizontal-outline'
                onClick={(event: any) => {
                  this.openActionSheet(event);
                }}
              ></app-icon>
            </div>
          ) : null}
        </ion-card-header>
      );
    }
  }

  /**
   * 渲染
   *
   * @memberof AppMobPortlet
   */
  render() {
    if (!this.c.controlIsLoaded) {
      return;
    }
    Object.assign(this.classNames, { [`portlet-${this.c.controlInstance.portletType.toLowerCase()}`]: true });
    return (
      <ion-card class={{ ...this.classNames }} style={this.getSize()}>
        {this.renderTitle()}
        <ion-card-content class='portlet-content'>{this.renderByPortletType()}</ion-card-content>
      </ion-card>
    );
  }
}

//  移动端门户部件组件
export const AppMobPortletComponent = GenerateComponent(AppMobPortlet, Object.keys(new AppMobPortletProps()));
